package com.hundsun.aitest.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hundsun.aitest.common.ApiPlatformConfig;
import com.hundsun.aitest.common.BladePlatformConfig;
import com.hundsun.aitest.model.ai.AutoCase;
import com.hundsun.aitest.model.ai.TestParameters;
import com.hundsun.aitest.model.ai.TestPoint;
import com.hundsun.aitest.model.blade.*;
import com.hundsun.aitest.model.plat.InterfaceDict;
import com.hundsun.aitest.service.BaoSongDBService;
import com.hundsun.aitest.service.DataBaseService;
import com.hundsun.aitest.service.TestCasesService;
import com.hundsun.aitest.util.HttpUtils;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.hundsun.aitest.common.Constants.*;

@Service
@Slf4j
public class TestCasesServiceImpl implements TestCasesService {

    private static final String API_URL_TEST_CASE = "https://blade.hundsun.com/openapi/design/importOfflineCase.json";
    private static final String API_URL_VARIABLE = "https://blade.hundsun.com/openapi/design/dealVariableData.json";
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private BladePlatformConfig.ProjectConfig projectConfig =  new BladePlatformConfig.ProjectConfig() ;

    @Autowired
    private ApiPlatformConfig apiPlatformConfig;

    @Autowired
    private DataBaseService dataBaseService;
    @Autowired
    BaoSongDBService baoSongDBService;

    @Autowired
    private TestInterfaceServiceImpl testInterfaceService;

    @Autowired
    BladePlatformConfig bladePlatformConfig;

    @Override
    public void updateProjectInfo(String project) {
//        Map<String, Object> content = YamlOperationUtils.readYaml("config/ThirdPlatformConfig.yaml");
//        Map<String, Object> bladeContent = (Map<String, Object>) content.get("BladePlatform");
        projectConfig = bladePlatformConfig.getBladePlatform().get(project);
    }

    private String uploadScript(String postUrl, String postParams){
        Map<String, String> header1 = new HashMap<>();
        header1.put("Content-Type", "application/json;charset=UTF-8");
        // 发送请求
        HttpResponse response = HttpRequest.get(postUrl)
                .addHeaders(header1)
                .body(postParams).execute();
        JSONObject responseResult = JSON.parseObject(response.body());
        log.info("新增脚本返回信息：{}", responseResult);
        String scriptId = "";
        if(responseResult.getInteger("code").equals(1000)) {
            net.minidev.json.JSONArray result0 = JsonPath.read(responseResult, "$..ID");
            if (!result0.isEmpty()) {
                scriptId = result0.get(0).toString();
            }
        }
        log.info("新建脚本后的脚本ID为：{}", scriptId);
        return scriptId;
    }

    /**
     * 新增测试脚本
     * @param interfaceDict : 脚本信息
     * @return
     */
    private String uploadScriptContent(InterfaceDict interfaceDict){
        String postUrl = "https://blade.hundsun.com/openapi/design/dealScriptDataV2.json";
        //Map<String, String> headers = interfaceDict.getHeaders();
        ScriptRequest postScriptParams = new ScriptRequest();
        postScriptParams.setNodePath(projectConfig.getScriptPath());
        postScriptParams.setApiToken(projectConfig.getApiKey());
        if(projectConfig.getAccount() != null || !projectConfig.getAccount().equals("")) {
            postScriptParams.setAccount(projectConfig.getAccount());
        }
        // 脚本内容
        JSONObject jsonData = new JSONObject();
        jsonData.put("请求方式", interfaceDict.getMethod());
        jsonData.put("根URL", "http1");
        jsonData.put("路径", interfaceDict.getUrl());
        jsonData.put("编码类型","UTF-8");
        ScriptContent scriptContent = new ScriptContent();
        scriptContent.setScriptType(25);
        scriptContent.setScriptName(interfaceDict.getScriptName());
        scriptContent.setScriptContent("http");
        scriptContent.setScriptRemark("http请求");
        scriptContent.setScriptJsonData(jsonData.toString());
        List<ScriptContent> scriptContents = new ArrayList<>();
        scriptContents.add(scriptContent);
        postScriptParams.setData(scriptContents);
        String postParams = JSON.toJSONString(postScriptParams);
        log.info("脚本内容是：{}", postParams);
        return this.uploadScript(postUrl, postParams);
    }

    private String uploadInitScriptContent() {
        String postUrl = "https://blade.hundsun.com/openapi/design/dealScriptDataV2.json";
        ScriptRequest postScriptParams = new ScriptRequest();
        postScriptParams.setNodePath(projectConfig.getScriptPath());
        postScriptParams.setApiToken(projectConfig.getApiKey());
        if(projectConfig.getAccount() != null || !projectConfig.getAccount().equals("")) {
            postScriptParams.setAccount(projectConfig.getAccount());
        }
        ScriptContent scriptContent = new ScriptContent();
        scriptContent.setScriptType(3);
        scriptContent.setScriptName("空脚本执行");
        scriptContent.setScriptContent("dbInit|,");
        scriptContent.setScriptRemark("空脚本执行");
        //scriptContent.setScriptJsonData(null);
        List<ScriptContent> scriptContents2 = new ArrayList<>();
        scriptContents2.add(scriptContent);
        postScriptParams.setData(scriptContents2);
        String postParams = JSON.toJSONString(postScriptParams);
        log.info("空脚本执行的内容是：{}", postParams);
        return this.uploadScript(postUrl, postParams);
    }

    /**
     * 新增测试脚本，若存在不会新增，只会返回ID
     * @param interfaceDict
     * @return
     */
    @Override
    public InterfaceDict queryScriptId(InterfaceDict interfaceDict) {
        if(interfaceDict.getScriptName() == null){
            // 查询接口文档中的接口信息，并返回
            interfaceDict = testInterfaceService.queryInterfaceDetail(interfaceDict.getInterfaceId());
        }
        // 不存在，则新增接口
        String scriptId = uploadScriptContent(interfaceDict);
        interfaceDict.setScriptId(scriptId);
        return interfaceDict;
    }

    /**
     * 根据测试点匹配接口信息，并将其接口上传到blade平台，返回blade平台上的接口ID
     * @param project   ： blade项目ID
     * @param testPoint ： 测试点
     * @return
     * @throws JsonProcessingException
     */
    @Override
    public InterfaceDict patternAndGetInterfaceDetail(String project, String testPoint) throws JsonProcessingException {
        this.updateProjectInfo(project);
        testInterfaceService.setProject(project);  // 更新项目ID
        dataBaseService.initProject(project);
        InterfaceDict interfaceDict = testInterfaceService.patternInterface(testPoint, true);
        interfaceDict = testInterfaceService.queryParamsDict(project, interfaceDict);
        apiPlatformConfig.addInterfaceDict(interfaceDict);
        InterfaceDict scriptContent = this.queryScriptId(interfaceDict);
        return scriptContent;
    }

    @Override
    public String uploadTestCase(TestCaseRequest request) {
        
        // Convert the request object to a JSON string using FastJSON
        String jsonRequest = JSON.toJSONString(request);
        log.info("调用blade时，传递的参数：\n{}",jsonRequest);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String result = HttpUtils.sendPostJsonRequest(API_URL_TEST_CASE, jsonRequest, headers);

        return result;
    }

    @Override
    public TestCaseRequest buildTestCaseRequest(String apiToken, String account, String nodePath, AutoCase autoCase,String attachInfo) {
        TestCaseRequest testCaseRequest = new TestCaseRequest();
        testCaseRequest.setApiToken(apiToken);
        testCaseRequest.setAccount(account);
        testCaseRequest.setNodePath(nodePath);
        String interfaceName= autoCase.getInterfaceName();
        testCaseRequest.setData(convertTestPointsToTestCaseData(autoCase,account,interfaceName,attachInfo));
        log.info("上传的参数是：{}", JSONUtil.parseObj(testCaseRequest));
        return testCaseRequest;
    }

    @Override
    public String uploadVarible(Variable request) {
        // Convert the request object to a JSON string using FastJSON
        String jsonRequest = JSON.toJSONString(request);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String result = HttpUtils.sendPostJsonRequest(API_URL_VARIABLE, jsonRequest, headers);
        log.info("上传的参数是：{}",jsonRequest);
        return result;
    }

    @Override
    public Variable buildVariableRequest(String apiToken, String account, String nodePath, String reportCode) {
        Variable  variables=new Variable();
        variables.setApiToken(apiToken);
        variables.setAccount(account);
        variables.setDataNode(nodePath);

        JSONArray reportResult = baoSongDBService.getReportInfo(reportCode);

        String reportName=reportResult.getJSONObject(0).getString("REPORT_NAME");
        String reportProcessId=baoSongDBService.getReportProcess(reportCode).getJSONObject(0).getString("ID");
        List<VariableData> vDataList=new LinkedList<>();
        VariableData vDataReportId=new VariableData();
        
        String reportIdSql = String.format("SELECT ID FROM URP_REPORT_INFO WHERE REPORT_CODE='%s'", reportCode);
        String parentModuleCode = reportResult.getJSONObject(0).getString("PARENT_MODULE_CODE");
        //获得管理人代码，通过URP_MANAGER_INFO获得的管理人代码，这里可以写实，用招商基金：cisp_org_code:12334567,fin_ins_code:11002255114401
        String managerCode = parentModuleCode.contains("CISP") ? "12334567" : "11002255114401";
        String bussinseeReportCode = "001." + parentModuleCode + "." + reportCode + "." + managerCode;

        String reportProcessIdSql = String.format("select ID from URP_REPORT_PROCESS where REPORT_CODE='%s' and BUSINESS_REPORT_CODE = '%s'", reportCode, bussinseeReportCode);
        vDataReportId.setVarName("varg_ai_report_id_"+reportCode);
        vDataReportId.setVarContent(reportIdSql);
        //数据源连接的名字固定
        vDataReportId.setVariableConnection("odbc");
        vDataReportId.setVariableRemark(reportName);
        vDataList.add(vDataReportId);
        VariableData vDataReportProcessId=new VariableData();
        vDataReportProcessId.setVarName("varg_ai_report_process_id_"+reportCode);
        vDataReportProcessId.setVarContent(reportProcessIdSql);
        vDataReportProcessId.setVariableConnection("odbc");
        vDataReportProcessId.setVariableRemark("");
        vDataList.add(vDataReportProcessId);
        VariableData vReportDate=new VariableData();
        vReportDate.setVarName("varg_ai_report_date");
        vReportDate.setVarContent("20240830");
        vReportDate.setVariableConnection("");
        vReportDate.setVariableRemark("");
        vDataList.add(vReportDate);

        variables.setData(vDataList);
        log.info("上传的参数是：{}",variables);


        return variables;
    }

    private List<TestCase> convertTestPointsToTestCaseData(AutoCase autoCase, String account, String interfaceName,String attachInfo) {
        if (autoCase == null) {
            return new ArrayList<>();
        }

        List<TestCase> testCaseDataList = new ArrayList<>();
        List<TestPoint> testPoints = autoCase.getTestPoints();

        for (TestPoint testPoint : testPoints) {
            String testPurpose = testPoint.getTestPurpose();
            TestParameters parameters = testPoint.getParameters();
            String sideType = testPoint.getCaseSideType().equals("反例") ? "1" : "0";
            String testResult = testPoint.getTestResult();
            String testPriority = testPoint.getCasePriority();
            String preSql = testPoint.getPreSql();
            String dbConnection = testPoint.getDbConnection();
            String afterSql = testPoint.getAfterSql();

            // 创建基本的TestCase对象
            TestCase testCase = createBaseTestCase(testPurpose, "2", testPriority, sideType, "0", "1", account);

            if ("2".equals(autoCase.getCaseType()) && testPoint.getPreSql().isEmpty()) {
                testCase.setCaseType("1");
            }

            List<Step> steps = new ArrayList<>();

            // 创建主步骤
            Step mainStep = new Step();
            StepDetails mainStepDetails = new StepDetails();
            mainStepDetails.setStepDes(testPurpose);
            mainStepDetails.setExpect(testResult);
            mainStepDetails.setPreSqlContent(createPreSqlContent(dbConnection, preSql));
            //通过接口名称来获得脚本id，如果是Auto类型的，直接传入，attachInfo为scriptid。如果是勾稽用例则通过getScriptContent获取scriptid
            if(autoCase.getCaseType().equals("1")&&attachInfo!=null){
                mainStepDetails.setScriptContent(attachInfo);
            }else{
                mainStepDetails.setScriptContent(getScriptContent(interfaceName));
            }

            if (autoCase.getCaseType().equals("2")) {
                // 创建前置步骤，勾稽用例attchinfo传的是勾稽编号
                Step preStep = createPreStep(attachInfo);
                steps.add(preStep);

                // 设置主步骤的数据内容,勾稽用例的勾稽检查步骤，参数没有嵌套，可以用通用的参数妆化逻辑
                if (parameters != null) {
                    mainStepDetails.setDataContent(createDataContent(parameters.getParameters()));
                }
                mainStepDetails.setCheckContent(createCheckContent(sideType,attachInfo));
                mainStep.setStepJson(mainStepDetails);
                steps.add(mainStep);

                // 创建后置步骤，仅能添加勾稽用例固定的后置添加！理想不应该放在 这里。在顶层应用层添加步骤！
                Step afterStep = createAfterStep();
                steps.add(afterStep);
            } else {
                // 设置主步骤的数据内容
                if (parameters != null) {
                    mainStepDetails.setDataContent(createDataContent(parameters.getParameters()));
                }
                mainStep.setStepJson(mainStepDetails);
                steps.add(mainStep);

                if(afterSql != null && !afterSql.isEmpty()){
                    Step afterStep2 = createAfterClearDataStep(afterSql, dbConnection);
                    steps.add(afterStep2);
                }
            }

            testCase.setStep(steps);
            testCaseDataList.add(testCase);
        }

        log.info("转化blade请求参数的结果，testCaseDataList={}", testCaseDataList);
        return testCaseDataList;
    }

    /**
     * 创建主步骤的数据内容
     *
     * @param  sideType 正反例: 0 正例，1反例;
     * @param attachInfo  勾稽规则的编号
     * @return
     */
    private List<CheckContent> createCheckContent(String sideType,String  attachInfo) {
        List<CheckContent> checkContents = new ArrayList<>();
        CheckContent checkContent = new CheckContent();
        //数据库连接先写死,在blade中配置的数据库连接名设置成“odbc”
        checkContent.setCheckConnection("odbc");
        String checkSql=String.format("select r.RESULT_STATUS from URP_DATACHECK_RESULT r join URP_DATACHECK_RULE ru on  r.RULE_ID=ru.ID  where r.REPORT_FLOW_ID=varc_data_0_id and ru.CHECK_CODE='%s'",attachInfo);
        checkContent.setDbCheckSql(checkSql);
        String expectStr="SRC->RESULT_STATUS="+(sideType.equals("0")?"pass":"not_pass");
        checkContent.setDbExpect(expectStr);
        checkContent.setDbSqlId("");
        checkContent.setDbSqlName("");
        checkContents.add(checkContent);
        return checkContents;
    }

    /**
     *
     * @param attachInfo 在勾稽用例种根据勾稽的编号发起报表
     * @return
     */
    private Step createPreStep(String  attachInfo) {
        // 实现增加勾稽前置步骤的逻辑
        Step preStep = new Step();
        StepDetails preStepDetails = new StepDetails();
        preStepDetails.setStepDes("报送任务发起");
        preStepDetails.setExpect("发起成功");
        //0:前置步骤
        preStepDetails.setPrecisionTest("0");
        preStepDetails.setScriptContent(getScriptContent(CHECK_PROCESS_START));
        preStepDetails.setDataContent(createCheckBeforeDataContent(attachInfo));
        preStep.setStepJson(preStepDetails);
        return preStep;
    }

    private Step createAfterClearDataStep(String sql, String dbLink) {
        Step afterStep = new Step();
        StepDetails afterStepDetails = new StepDetails();
        afterStepDetails.setStepDes("清理测试数据");
        afterStepDetails.setExpect("清理成功");
        List<PreSqlContent> preSqlContents = new ArrayList<>();
        PreSqlContent preSqlContent = new PreSqlContent();
        preSqlContent.setContent(sql);
        preSqlContent.setId("");
        preSqlContent.setType("2");
        preSqlContent.setConnection(dbLink);
        preSqlContents.add(preSqlContent);
        afterStepDetails.setPreSqlContent(preSqlContents);
        // 1：后置步骤
        afterStepDetails.setPrecisionTest("1");
        // String scriptId = "43a823f65d234fb7bf9d127b1b5c9eef";
        String scriptId = this.uploadInitScriptContent();
        afterStepDetails.setScriptContent(scriptId);
        //afterStepDetails.setDataContent(createCheckAfterDataContent());
        afterStep.setStepJson(afterStepDetails);
        return afterStep;
    }

    private Step createAfterStep() {
        // Todo: 实现增加勾稽后置步骤的逻辑
        Step afterStep = new Step();
        StepDetails afterStepDetails = new StepDetails();
        afterStepDetails.setStepDes("报送任务关闭");
        afterStepDetails.setExpect("关闭成功");
        // 1：后置步骤
        afterStepDetails.setPrecisionTest("1");
        afterStepDetails.setScriptContent(getScriptContent(CHECK_PROCESS_AFTER));
        afterStepDetails.setDataContent(createCheckAfterDataContent());
        afterStep.setStepJson(afterStepDetails);
        return afterStep;
    }

    private TestCase createBaseTestCase(String testPurpose, String caseType, String casePriority, String caseSideType, String caseDetailType, String caseLayer, String account) {
        TestCase testCase = new TestCase();
        testCase.setCaseName(testPurpose);
        // 用例类型2：自动化
        testCase.setCaseType(caseType);
        // 用例级别：P0~P3
        testCase.setCasePrior(casePriority);
        // 正反例：0正例，1反例
        testCase.setCaseSideType(caseSideType);
        // 0：功能
        testCase.setCaseDetailType(caseDetailType);
        // 1: 已启用
        testCase.setCaseState("1");
        testCase.setCaseLayer(caseLayer);
        testCase.setCaseHeader(account);
        return testCase;
    }

    private List<PreSqlContent> createPreSqlContent(String dbConnection, String content) {
        PreSqlContent preSqlContent = new PreSqlContent();
        preSqlContent.setConnection(dbConnection);
        preSqlContent.setContent(content);
        preSqlContent.setType("2");            // Todo: 类型为什么是2，待明确。
        List<PreSqlContent> listSql = new ArrayList<>();
        listSql.add(preSqlContent);
        return listSql;
    }

    private String getScriptContent(String interfaceName) {

        String scriptContent="";
        if(CHECK_INTERFACE_NAME.equals(interfaceName)){
            scriptContent="c4932a40dbb44146b909d91043e46c28";
        }else if(CHECK_PROCESS_START.equals(interfaceName)){
            scriptContent="1cc028991bac4a20b15d0fb97153d8d7";
        } else if(CHECK_PROCESS_AFTER.equals(interfaceName)){
            scriptContent="45ed5771a53c4c09bb80c2c8f2c141ff";
        } else
        {
            //默认的接口为空
            scriptContent="";

        }
        return scriptContent;
    }


    //缺省的用例内容，目前没有支持参数的对象嵌套。
    public DataContent  createDataContent(Map<String, Object> parameters) {
        List<Map<String, List<List<String>>>> dataArrContent = new ArrayList<>();

        // Initialize the Sheet1 content with a dynamic header based on the keys in parameters
        List<String> header = new ArrayList<>();
        header.add("0"); // Assuming this is a fixed column
        header.add("序号"); // Assuming this is a fixed column
        header.add(""); // Assuming this is a fixed column
        header.addAll(parameters.keySet()); // Add all keys from the parameters map as headers

        List<List<String>> sheet0Content = new ArrayList<>();
        sheet0Content.add(header); // Add the header to the sheet content

        // 子表参数说明
        List<String> subParamComentRow = new ArrayList<>();
        subParamComentRow.add("1");
        subParamComentRow.add("参数说明");
        subParamComentRow.add("");

        sheet0Content.add(subParamComentRow);

        // Process each entry in the parameters map and add them as a single row
        List<String> row = new ArrayList<>();
        row.add("2"); // Assuming this is a fixed value
        row.add("1"); // Assuming this is a fixed value
        row.add(""); // Assuming this is a fixed value
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            Object value = entry.getValue();

            // Assuming value is a String, convert it to String if not already
            String stringValue="";
            if(value!=null){
                 stringValue = value.toString();
            }


            // Add the value to the row
            row.add(stringValue);
        }

        sheet0Content.add(row); // Add the complete row to the sheet content

        // Create Sheet1
        Map<String, List<List<String>>> sheet1 = new HashMap<>();
        sheet1.put("Sheet0", sheet0Content);

        // Add Sheet1 to the main list
        dataArrContent.add(sheet1);

        // Assuming DataContent has a constructor or setter that accepts the dataArrContent
        return new DataContent("", "2", "", dataArrContent);
    }

    /**
     * 用例创建构建检查的前置接口startWfProcessBatch的参数
     * @param checkCode 勾稽编号
     * @return
     */
    private DataContent createCheckBeforeDataContent(String checkCode) {
        String reportCode=checkCode.split("\\.")[0];
        //写死，后面根据不同的类型取不同的值，生成的数据日期统一定为20240830。
        String reportDate="varg_ai_report_date";
        //String reportId=baoSongDBService.getReportInfo(reportCode).getJSONObject(0).getString("ID");
        String reportId="varg_ai_report_id_"+reportCode;
        String reportName=baoSongDBService.getReportInfo(reportCode).getJSONObject(0).getString("REPORT_NAME");
        //String reportProcessId=baoSongDBService.getReportProcess(reportCode).getJSONObject(0).getString("ID");
        String reportProcessId="varg_ai_report_process_id_"+reportCode;

        Map<String, Object> parameters = new LinkedHashMap<>();
        parameters.put("期望", "data_0_task_start_info=*操作成功！*");
        parameters.put("env_id", "001");
        parameters.put("is_last_period","0");
        parameters.put("user_no","admin");
        parameters.put("start_report_process_list(Array)", new LinkedHashMap<String, Object>() {{
            put("期望","");
            put("busi_date", reportDate);
            //Todo 获得管理人代码，通过URP_MANAGER_INFO获得的管理人代码，这里可以写实，用招商基金：cisp_org_code:12334567,fin_ins_code:11002255114401
            put("busi_sort_name", "招商基金");
            put("remark", "");
            put("report_code",reportCode);
            put("report_date",reportDate);
            put("report_flow_id","");
            put("report_id",reportId);
            put("report_info_id",reportId);
            put("report_process_id",reportProcessId);
            put("require_time",reportDate);
            put("variables_map(Object)", new LinkedHashMap<String, Object>() {{
                put("期望","");
                put("urp_ins_context(Object)", new LinkedHashMap<String, Object>() {{
                    put("期望","");
                    put("business_report_code", "");
                    put("pro_ng_id", "");
                    put("report_code", reportCode);
                    put("report_date",reportDate);
                    put("report_flow_id","");
                    put("report_info_id",reportId);
                    put("report_name",reportName);
                    //Todo 待明确
                    put("report_process_id","");
                    put("require_time",reportDate);
                }});
            }});
        }});

        // 构建输出格式
        List<Map<String, List<List<String>>>> dataArrContent = new ArrayList<>();

        // 构建主表（Sheet1）
        Map<String, List<List<String>>> sheet1 = buildSheet(parameters, "Sheet0");
        dataArrContent.add(sheet1);

        // 处理所有嵌套结构
        processNestedStructure(dataArrContent, parameters, "");

        return new DataContent("", "2,2,2,2", "", dataArrContent);
    }

    private DataContent createCheckAfterDataContent() {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("期望", "error_code=000000");
        parameters.put("env_id", "001");
        parameters.put("user_no","admin");
        parameters.put("data(Object)", new HashMap<String, Object>() {{
            put("instance_ids", "varc_data_0_wf_variables_map_urp_ins_context_wf_instance_id");
            put("remark", "v");
            put("user_id", "admin");

        }});

        // 构建输出格式
        List<Map<String, List<List<String>>>> dataArrContent = new ArrayList<>();

        // 构建主表（Sheet0）
        Map<String, List<List<String>>> sheet1 = buildSheet(parameters, "Sheet0");
        dataArrContent.add(sheet1);

        // 处理所有嵌套结构
        processNestedStructure(dataArrContent, parameters, "");

        return new DataContent("", "2,2", "", dataArrContent);
    }

    private static void processNestedStructure(List<Map<String, List<List<String>>>> dataArrContent, Map<String, Object> parameters, String prefix) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            String key = entry.getKey();
            String currentPrefix = prefix.isEmpty() ? key : prefix + "_" + key;

            if (entry.getValue() instanceof Map) {
                Map<String, List<List<String>>> subSheet = buildSheet((Map<String, Object>) entry.getValue(), key.replaceAll("\\(.*?\\)", ""));
                dataArrContent.add(subSheet);
                processNestedStructure(dataArrContent, (Map<String, Object>) entry.getValue(), currentPrefix);
            } else if (entry.getValue() instanceof List) {
                processNestedList(dataArrContent, (List<Object>) entry.getValue(), key.replaceAll("\\(.*?\\)", ""));
            }
        }
    }

    private static void processNestedList(List<Map<String, List<List<String>>>> dataArrContent, List<Object> nestedList, String prefix) {
        for (Object item : nestedList) {
            if (item instanceof Map) {
                Map<String, List<List<String>>> subSheet = buildSheet((Map<String, Object>) item, prefix.replaceAll("\\(.*?\\)", ""));
                dataArrContent.add(subSheet);
                processNestedStructure(dataArrContent, (Map<String, Object>) item, prefix);
            } else if (item instanceof List) {
                processNestedList(dataArrContent, (List<Object>) item, prefix);
            } else {
                Map<String, List<List<String>>> subSheet = new HashMap<>();
                List<List<String>> subSheetRows = new ArrayList<>();
                subSheetRows.add(Arrays.asList("1", "1", "", item.toString()));
                subSheet.put(prefix, subSheetRows);
                dataArrContent.add(subSheet);
            }
        }
    }

    private static Map<String, List<List<String>>> buildSheet(Map<String, Object> subMap, String prefix) {
        Map<String, List<List<String>>> subSheet = new LinkedHashMap<>();
        List<List<String>> subSheetRows = new ArrayList<>();

        // 子表表头
        List<String> subHeaderRow = new ArrayList<>();
        subHeaderRow.add("0");
        subHeaderRow.add("序号");
        //是主sheet，加一列参数说明列
        if(prefix.equals("Sheet0")){
            subHeaderRow.add("");
        }
        subHeaderRow.addAll(subMap.keySet());
        subSheetRows.add(subHeaderRow);

        // 子表参数说明
        List<String> subParamComentRow = new ArrayList<>();
        subParamComentRow.add("1");
        subParamComentRow.add("参数说明");
        //是主sheet，加一列参数说明列
        if(prefix.equals("Sheet0")) {
            subParamComentRow.add("");
        }
        subSheetRows.add(subParamComentRow);

        // 子表值行
        List<String> subValueRow = new ArrayList<>();
        subValueRow.add("2");
        subValueRow.add("1");
        //是主sheet，加一列参数说明列
        if(prefix.equals("Sheet0")){
            subValueRow.add("");
        }
        subValueRow.addAll(subMap.entrySet().stream()
                .map(e -> formatValue(e, prefix))
                .collect(Collectors.toList()));
        subSheetRows.add(subValueRow);

        subSheet.put(prefix, subSheetRows);
        return subSheet;
    }


//    private static String formatValue(Map.Entry<String, Object> entry, String prefix) {
//        if (entry.getValue() instanceof Map) {
//            return prefix + "_" + entry.getKey() + "|1";
//        } else {
//            return entry.getValue().toString();
//        }
//    }
private static String formatValue(Map.Entry<String, Object> entry, String prefix) {
    if (entry.getValue() instanceof Map) {
        return entry.getKey().replaceAll("\\(.*?\\)", "") + "|" + "1"; // 使用当前键名作为表名的一部分
    } else {
        return entry.getValue().toString();
    }
}


    private StepDetails createPreStepDataContent(AutoCase autoCase, TestPoint testPoint) {
        // 返回前置步骤的数据内容
        // 示例：
        return null;
    }
}